package task

import (
	"time"
)

var TaskList map[int]Task
var newId int

func Init() {
	TaskList = make(map[int]Task, 0)
	newId = 0
}
func GetTask(id int) (Task, bool) {
	if task, ok := TaskList[id]; ok {
		return task, ok
	} else {
		return task, ok
	}
}
func Len() int {
	return len(TaskList)
}
func Add(timev int64, taskType int, taskVaule string) (nid int) {
	if taskVaule == "" {
		return -1
	}
	var task Task
	task.Id = newId
	newId = newId + 1
	task.Time = timev
	task.TaskType = taskType
	task.TaskVaule = taskVaule
	//设置下次运行时间
	task.Update()
	TaskList[task.Id] = task
	return task.Id
}
func Del(id int) bool {
	if _, ok := TaskList[id]; !ok {
		return false
	}
	delete(TaskList, id)
	return true
}
func Run() {
	for _, task := range TaskList {
		if task.NextRunTime < time.Now().Unix() {
			TaskList[task.Id] = task.Do()
		}
	}
	time.Sleep(1 * time.Second)
	Run()
}
